
///Normale
varying vec4 normal;
///Posizione
varying vec4 point;

///Osservatore
uniform vec4 viewpoint;

void main(void)
{
    int i;

    vec4 ambient = vec4(0.0, 0.0, 0.0, 0.0);
    vec4 specular = vec4(0.0, 0.0, 0.0, 0.0);
    vec4 diffuse = vec4(0.0, 0.0, 0.0, 0.0);

    vec4 n = normalize(normal);
    vec4 v = normalize(viewpoint - point);
    float shininess = 8.0;

    ///Componente ambientale
    for ( i = 0; i < 1; i ++ ) {
        ambient += gl_LightSource[i].ambient * gl_Color;

        ///Componente diffusiva
        vec4 l = normalize(gl_LightSource[i].position - point);
        float NdotL = dot(n,l);
        if ( NdotL >= 0.0 )
            diffuse += gl_LightSource[i].diffuse * gl_Color * 0.5;

        ///Componente speculare
        ///vec4 h = normalize(l + v);
        vec3 hv = gl_LightSource[0].halfVector.xyz;
        vec4 h = vec4(hv.x, hv.y, hv.z, 1.0);
        h = normalize(h);
        //if ( NdotL > 0.0 )
        float NdotH = max(dot(n,h), 0.0);
        if (NdotH >= 0.95)
            specular += gl_LightSource[0].specular * gl_Color * pow(1.0, shininess);
    }

    gl_FragColor = ambient + diffuse + specular;

    /*vec3 x = dFdy(gl_FragCoord);
    vec3 y = dFdx(gl_FragCoord);
    vec3 flatN = normalize(cross(x,y));

    gl_FragColor = gl_Color * fwidth(gl_FragCoord.z);*/

    vec4 border = vec4(0.2, 0.2, 0.2, 0.8);
    //float x = fwidth( gl_FragCoord.z );

    vec4 mpoint = gl_ModelViewMatrix * point;

    float x = fwidth( mpoint.z );

    //gl_FragColor = gl_Color * x;

    //if ( x > 0.00005 )
    //    gl_FragColor = blue;

    if ( x > 0.006 )
        gl_FragColor = border;

    //if ( abs(log(x)) < 10.0 )
    //    gl_FragColor = blue;

}
